<template>
  <div class="app-container">
    <el-form 
      :model="queryParams" 
      style="border-bottom: 1px solid #c9c9c9; margin-bottom: 30px;" 
      ref="queryRef" 
      :inline="true" 
      v-show="showSearch" 
      label-width="68px"
    >
      <el-form-item label="计划名称" prop="planName">
        <el-input
          v-model="queryParams.planName"
          placeholder="请输入计划名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item style="width: 300px;" label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
          <el-option
            v-for="dict in sys_job_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button 
          type="primary"  
          style="background-color: #266FE8; color: white;" 
          @click="handleQuery"
        >搜索</el-button>
        <el-button @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row style="display: flex; justify-content: flex-end;" :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          style="width: 150px; background-color: #266FE8; color: white;"
          plain
          @click="handleAdd"
          v-hasPermi="['system:plan:add']"
        >新增护理计划</el-button>
      </el-col>
    </el-row>

    <el-table 
      v-loading="loading" 
      :data="planList" 
      @selection-change="handleSelectionChange"
    >
      <el-table-column label="序号" align="center" prop="id" />
      <el-table-column label="计划名称" align="center" prop="planName" />
      <el-table-column label="创建人" align="center" prop="sysUser.nickName" />
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="status">
        <template #default="scope">
          <dict-tag :options="sys_job_status" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button 
            link 
            type="primary" 
            :style="{
              'display': 'inline-block',
              'margin-right': '5px',
              'color': scope.row.status === 1 ? '#c0c4cc' : 'red',
              'cursor': scope.row.status === 1 ? 'not-allowed' : 'pointer'
            }" 
            :disabled="scope.row.status == 1"
            @click="handleDelete(scope.row)" 
            v-hasPermi="['system:plan:remove']"
          >删除</el-button>
          <el-button 
            link 
            type="primary"  
            :style="{
              'display': 'inline-block',
              'margin-right': '5px',
              'color': scope.row.status === 1 ? '#c0c4cc' : '',
              'cursor': scope.row.status === 1 ? 'not-allowed' : 'pointer'
            }" 
            :disabled="scope.row.status == 1"
            @click="handleUpdate(scope.row)" 
            v-hasPermi="['system:plan:edit']"
          >编辑</el-button>
          <el-button link type="primary" @click="check(scope.row)">查看</el-button>
          <el-button 
            link 
            type="primary"   
            :style="{color: scope.row.status ? '' : 'red'}" 
            @click="changeStatus(scope.row)" 
            v-hasPermi="['system:plan:edit']"
          >{{ scope.row.status ? '启用' : '禁用' }}</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改护理计划对话框 -->
    <el-dialog :title="title" v-model="open" width="800px" append-to-body>
      <el-form ref="planRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item 
          label="计划名称" 
          prop="planName"
          :rules="[
            { required: true, message: '请输入计划名称', trigger: 'blur' },
            { max: 10, message: '最多输入10个字符', trigger: 'blur' },
            { validator: validateLevelNameUnique, trigger: ['blur', 'change'] }
          ]"
        >
          <el-input v-model="form.planName" placeholder="请输入护理计划名称" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="form.status" placeholder="请选择状态">
            <el-option
              v-for="dict in sys_job_status"
              :key="dict.value"
              :label="dict.label"
              :value="parseInt(dict.value)"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="护理项目" prop="item">
          <div class="nursing-table">
            <!-- 表头 -->
            <div class="table-header">
              <div>护理项目名称</div>
              <div>期望服务时间</div>
              <div>执行周期</div>
              <div>执行频次（次）</div>
              <div>操作</div>
            </div>
            <!-- 表格行：循环渲染护理项目数组 -->
            <div
              v-for="(item , index) in form.nursingItems"
              :key="index"
              class="table-row"
            >
              <!-- 护理项目名称下拉选择 -->
              <el-select v-model="item.nursingItemId" placeholder="请选择项目">
                <el-option
                  v-for="dict in itemList"
                  :key="dict.id"
                  :label="dict.name"
                  :value="dict.id"
                ></el-option>
              </el-select>
              <!-- 期望服务时间选择 -->
              <el-time-picker
                v-model="item.serviceTime"
                format="HH:mm"
                value-format="HH:mm"
                placeholder="选择时间"
                style="width: 120px"
              />
              <!-- 执行周期下拉选择（value统一为数字，与后端匹配） -->
              <el-select
                v-model="item.executionCycle"
                placeholder="请选择"
                style="width: 100px"
              >
                <el-option label="每日" value="1"></el-option>
                <el-option label="每周" value="2"></el-option>
                <el-option label="每月" value="3"></el-option>
              </el-select>
              <!-- 执行频次输入 -->
              <el-input
                v-model.number="item.executionFrequency"
                type="number"
                min="1"
                placeholder="频次"
                style="width: 80px"
              />
              <!-- 操作按钮（新增/删除） -->
              <div class="operate-btns">
                <el-button
                  v-if="form.nursingItems.length > 1"
                  icon="el-icon-minus"
                  @click="removeNursingItem(index)"
                >删除</el-button>
                <el-button
                  v-if="index === form.nursingItems.length - 1"
                  icon="el-icon-plus"
                  @click="addNursingItem"
                >增加</el-button>
              </div>
            </div>
          </div>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 查看信息弹窗 -->
    <el-dialog 
      title="查看护理计划"  
      v-model="openView" 
      width="800px" 
      append-to-body
    >
      <el-form 
        :model="viewForm" 
        label-width="80px"
        disabled  
      >
        <el-form-item label="计划名称">
          {{ viewForm.planName || '无' }}
        </el-form-item>
        <el-form-item label="护理项目">
          <div class="nursing-table">
            <div class="table-header">
              <div>护理项目名称</div>
              <div>期望服务时间</div>
              <div>执行周期</div>
              <div>执行频次（次）</div>
            </div>
            <div
              v-for="(item, index) in viewForm.nursingItems"
              :key="index"
              class="table-row"
            >
              <div>{{ getNursingName(item.nursingItemId) || '未选择' }}</div>
              <div>{{ item.serviceTime || '未设置' }}</div>
              <div>{{ cycleMap[item.executionCycle] || '未设置' }}</div>
              <div>{{ item.executionFrequency || '0' }}</div>
            </div>
          </div>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="openView = false">关 闭</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Plan">
import { ref, reactive, getCurrentInstance } from "vue";
import { toRefs } from "vue";
import { listPlan, getPlan, delPlan, addPlan, updatePlan } from "@/api/system/plan";
import { listItem } from "@/api/le/item";
import { listLevel_plan } from "@/api/le/itemplan";
import { useUserStore } from '@/store/modules/user';

// 初始化实例和工具
const { proxy } = getCurrentInstance();
const { sys_job_status } = proxy.useDict('sys_job_status');
const userStore = useUserStore();

// 响应式数据定义（核心：直接操作reactive源数据确保响应式）
const data = reactive({
  // 查询参数
  queryParams: {
    pageNum: 1,
    pageSize: 1000,
    planName: null,
    status: null,
  },
  // 表单数据（编辑/新增共用）
  form: { 
    id: null,
    isDeleted: 0,
    planName: "",
    creator: null,
    status: null,
    originalPlanName: undefined, // 用于名称重复校验的原始值
    nursingItems: [ // 默认初始化一条护理项目
      {
        id: null,
        nursingItemId: '',
        serviceTime: '08:00',
        executionCycle: '2', // 默认为"每周"（value=2与下拉框匹配）
        executionFrequency: 1,
      }
    ]
  },
  // 表单校验规则
  rules: {
    planName: [
      { required: true, message: "计划名称不能为空", trigger: "blur" }
    ],
  }
});

// 解构响应式数据（使用toRefs保持响应式）
const { queryParams, form, rules } = toRefs(data);

// 其他状态管理
const planList = ref([]);
const open = ref(false);
const openView = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const itemList = ref([]); // 护理项目下拉数据源

// 查看弹窗数据
const viewForm = reactive({
  planName: '',
  nursingItems: []
});
const cycleMap = { '1': '每日', '2': '每周', '3': '每月' }; // 周期映射（注意key为字符串，与下拉框value一致）

// 获取护理项目名称（通过ID映射）
const getNursingName = (id) => {
  const item = itemList.value.find(dict => dict.id === id);
  return item ? item.name : '';
};

/** 查询护理计划列表 */
function getList() {
  loading.value = true;
  listPlan(queryParams.value).then(response => {  
    console.log(response);
    planList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

/** 自定义校验：计划名称重复校验 */
function validateLevelNameUnique(rule, value, callback) {
  const currentValue = value.trim();
  if (!currentValue) return callback();

  const isEdit = !!form.value.id && form.value.originalPlanName !== undefined;
  // 编辑时名称未修改，直接通过
  if (isEdit && currentValue === form.value.originalPlanName) {
    return callback();
  }

  // 校验是否与现有计划重名
  const isDuplicate = planList.value.some(plan => {
    if (isEdit) return plan.planName === currentValue && plan.id !== form.value.id;
    return plan.planName === currentValue;
  });

  isDuplicate ? callback(new Error('该计划名称已存在，请更换')) : callback();
}

/** 取消按钮 */
function cancel() {
  open.value = false;
  reset();
}

/** 获取护理项目下拉列表 */
function getItemList() {
  listItem({status:1,pageSize:1000}).then(response => {
    itemList.value = response.rows;
  });
}

/** 添加护理项目行 */
function addNursingItem() {
  form.value.nursingItems.push({
    id: null,
    nursingItemId: '',
    serviceTime: '08:00',
    executionCycle: '2', // 默认为每周
    executionFrequency: 1,
  });
}

/** 删除护理项目行 */
function removeNursingItem(index) {
  form.value.nursingItems.splice(index, 1);
}

/** 表单重置（关键：直接操作reactive源数据） */
function reset() {
  data.form = { 
    id: null,
    isDeleted: 0,
    planName: "",
    creator: null,
    status: null,
    originalPlanName: undefined,
    nursingItems: [ // 重置时强制初始化一条默认数据
      {
        id: null,
        nursingItemId: '',
        serviceTime: '08:00',
        executionCycle: '2',
        executionFrequency: 1,
      }
    ]
  };
  proxy.resetForm("planRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置查询条件 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

/** 多选框选中处理 */
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length !== 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  form.value.creator = userStore.id; // 若依中用户ID为userId
  open.value = true;
  title.value = "添加护理计划";
}

/** 编辑按钮操作（核心修复：确保空数据时默认数据生效） */
function handleUpdate(row) {
  reset(); // 先重置表单，初始化默认nursingItems
  const _id = row.id || ids.value;

  // 加载护理项目关联数据
  listLevel_plan({ nursingPlanId: row.id }).then(response => {
    if (response.rows.length === 0) {
      // 无数据时，使用reset初始化的默认数据（已在data.form中）
      console.log("护理项目为空，使用默认数据");
    } else {
      // 有数据时，覆盖默认数据（直接操作data.form确保响应式）
      data.form.nursingItems = response.rows.map(item => ({
        ...item,
        // 确保周期为字符串（与下拉框value类型匹配）
        executionCycle: item.executionCycle?.toString() || '2'
      }));
    }
  });

  // 加载计划基本信息
  getPlan(_id).then(response => {
    const planData = response.data;
    // 合并基本信息与护理项目（保留已处理的nursingItems）
    data.form = {
      ...planData,
      originalPlanName: planData.planName, // 存储原始名称用于校验
      nursingItems: data.form.nursingItems // 使用上面处理后的护理项目
    };
    open.value = true;
    title.value = "修改护理计划";
  });
}

/** 查看按钮操作 */
function check(row) {
  viewForm.planName = row.planName;
  openView.value = true;
  listLevel_plan({ nursingPlanId: row.id }).then(response => {
    viewForm.nursingItems = response.rows.length === 0 
      ? [{ nursingItemId: '', serviceTime: '', executionCycle: '', executionFrequency: 0 }]
      : response.rows;
  });
}

/** 提交表单 */
function submitForm() {
  console.log(form.value);
  proxy.$refs["planRef"].validate(valid => {
    if (valid) {
      if (form.value.id) {
        updatePlan(form.value).then(() => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addPlan(form.value).then(() => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm(`是否确认删除护理计划编号为"${_ids}"的数据项？`).then(() => {
    return delPlan(_ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

/** 状态切换（启用/禁用） */
function changeStatus(row) {
  const targetStatus = row.status ? 0 : 1;
  const confirmMsg = targetStatus === 0 
    ? `是否确认禁用护理计划编号为"${row.id}"的数据项？`
    : `是否确认启用护理计划编号为"${row.id}"的数据项？`;

  proxy.$modal.confirm(confirmMsg).then(() => {
    return updatePlan({ ...row, status: targetStatus });
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("状态修改成功");
  }).catch(() => {});
}

/** 初始化加载数据 */
getItemList();
getList();
</script>

<style scoped>
.nursing-table {
  width: 700px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  margin-top: 10px;
}
.table-header,
.table-row {
  display: flex;
  align-items: center;
  padding: 10px;
  border-bottom: 1px solid #ebeef5;
}
.table-header > div {
  flex: 1;
  font-weight: bold;
  text-align: center;
}
.table-row > div,
.table-row > .el-select,
.table-row > .el-time-picker,
.table-row > .el-input {
  flex: 1;
  margin: 0 5px;
  text-align: center; 
}
.operate-btns {
  display: flex;
  justify-content: center;
}
</style>